package com.npave.zryhadapter.controller.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.scheme.WxMaGenerateSchemeRequest;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.npave.zryhadapter.entity.to.WxAuthTO;
import com.npave.zryhadapter.exceptions.BusinessException;
import com.npave.zryhadapter.response.ReturnMsg;
import com.npave.zryhadapter.response.vo.JsonObj;
import com.npave.zryhadapter.utils.JacksonUtil;
import com.npave.zryhadapter.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/auth")
@Validated
@Slf4j
public class AuthController {

    @Autowired
    private WxMaService wxMaService;

    @Value("${serverInfo.url}")
    public String serverUrl;

    @PostMapping("/wx")
    public Object authByWx(@RequestBody WxAuthTO wxAuthTO,
                            HttpServletResponse response){

        if (null == wxAuthTO || StringUtil.isBlank(wxAuthTO.getCode()))
            throw new BusinessException(ReturnMsg.PARAM_ERROR);

        if (!wxMaService.switchover(wxAuthTO.getAppid())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", wxAuthTO.getAppid()));
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxAuthTO.getCode());

            log.info("session : {}", session);
            HttpResponse httpResponse = HttpRequest.post(serverUrl + "/api/auth/wx")
                    .body(JacksonUtil.toJsonStr(session))
                    .timeout(5000)
                    .execute();
            if (httpResponse.isOk()) {

                response.setHeader("X-Token", httpResponse.header("X-Token"));
                return httpResponse.body();
            }

            throw new RuntimeException();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }



}
